<?php

namespace common\models\user;

use Yii;
use common\helpers\StringHelper;
use common\helpers\ArrayHelper;
use common\helpers\Url;
use common\models\teacher\Teacher;

/**
 * This is the model class for table "{{%user_meta}}".
 *
 * @property int $id
 * @property string $nickname
 * @property string $realname
 * @property string $mobile
 * @property string $email
 * @property string $avatar
 * @property string $cover
 * @property int $gender
 * @property string $signature
 * @property string $birthday
 * @property int $marriage
 * @property int $children
 * @property string $location
 * @property int $role_id
 * @property int $ip
 * @property int $created_at
 * @property int $updated_at
 */
class UserMeta extends \common\base\ActiveRecord {

    use \common\traits\TimestampBehavior;
    use \common\traits\QueryInstanceActiveRecord;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%user_meta}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['id'], 'required'],
            [['id', 'gender', 'marriage', 'children', 'role_id', 'ip', 'created_at', 'updated_at'], 'integer'],
            [['birthday'], 'safe'],
            [['nickname'], 'string', 'max' => 32],
            [['realname'], 'string', 'max' => 50],
            [['mobile', 'email', 'avatar', 'cover'], 'string', 'max' => 255],
            [['signature'], 'string', 'max' => 128],
            [['location'], 'string', 'max' => 64],
            [['id'], 'unique'],
            [['nickname'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'nickname' => '昵称',
            'realname' => '姓名',
            'mobile' => '手机号',
            'email' => '邮箱',
            'avatar' => '头像',
            'cover' => '空间封面',
            'gender' => '性别',
            'signature' => '个人签名',
            'birthday' => '出生日期',
            'marriage' => '婚姻状况',
            'children' => '子女数量',
            'location' => '位置',
            'role_id' => '身份',
            'ip' => 'IP',
            'created_at' => '注册时间',
            'updated_at' => '最后修改时间',
        ];
    }

    public function getAccount() {
        return $this->hasOne(User::className(), ['id' => 'id']);
    }

    public function getEducater() {
        return $this->hasOne(Teacher::className(), ['user_id' => 'id']);
    }

    public function getUsername() {
        if ($this->nickname) {
            return $this->nickname;
        }
        return $this->account ? $this->account->username : '--';
    }

    /**
     * 过滤手机号敏感字段
     * @inheritdoc
     */
    public function decryptMobile($mask = true) {
        $mobile = Yii::$app->security->decryptMaster($this->mobile);
        if ($mask !== false) {
            return StringHelper::maskChar($mobile, 3, 2);
        }
        return $mobile;
    }

    /**
     * @inheritdoc
     */
    public function setMobile($mobile) {
        if ($mobile) {
            /* @var $security \common\base\Security */
            $security = Yii::$app->security;
            $this->mobile = $security->encryptMaster($mobile);
        }
    }

    /**
     * @inheritdoc
     */
    public function setAvatar($avatar = null) {
        $this->avatar = $avatar !== null ? $avatar : '/attachments/avatar/default.jpg';
    }

    /**
     * @inheritdoc
     */
    public function setUniqueNickname($nickname = null) {
        if ($nickname) {
            $rand = '';
            do {
                $exists = static::find()->where(['nickname' => $nickname . $rand])->exists();
                if ($exists) {
                    $rand = Url::toShort(microtime(true));
                }
            } while ($exists);
            $this->nickname = $nickname . $rand;
        }
    }

    public function getHobbys() {
        return $this->hasMany(UserHobby::className(), ['user_id' => 'id']);
    }

    public function getCategorys() {
        return $this->hasMany(\common\models\course\CourseCategory::className(), ['id' => 'course_category_id'])
        ->via('hobbys');
    }

    public function getHobby() {
        return ArrayHelper::getColumn($this->categorys, 'name');
    }

    /**
     * 融云TOKEN
     * @return 
     */
    public function getImToken() {
        return $this->hasOne(UserIm::className(), ['user_id' => 'id'])
        ->andWhere([
            'or',
            ['expired_at' => 0],
            ['>', 'expired_at', time()]
        ]);
    }

    public function getRongCloudToken() {
        if ($this->imToken && $this->imToken->im_token) {
            return $this->imToken->im_token;
        }
        $im = UserIm::findOrNew([
            'user_id' => $this->id
        ]);
        $rongyun = Yii::$app->rongyun->transport('user');
        $avatar = $this->avatar ?: '/attachments/avatar/default.jpg';
        $token = $rongyun->getToken($this->id, $this->username, Url::toRemote($avatar));
        if ($token !== false && isset($token['token'])) {
            $im->im_token = $token['token'];
            if (!$im->save()) {
                return '';
            }
            return $token['token'];
        }
        return '';
    }

    public function fields() {
        return [
            'id',
            'nickname' => 'username',
            'realname' => function() {
                return (string) $this->realname;
            },
            'mobile' => function() {
                if ($this->mobile) {
                    return $this->decryptMobile();
                }
                return '';
            },
            'avatar' => function() {
                return Url::toRemote($this->avatar);
            },
            'cover' => function() {
                return Url::toRemote($this->cover);
            },
            'rongyun_token' => 'rongCloudToken',
            'gender',
            'signature',
            'birthday',
            'location',
            'role_id',
            'location',
            'marriage',
            'children',
            'register_time' => 'created_at',
            'hobby',
            'teach_scopes' => function() {
                if ($this->role_id != Teacher::ROLE_ID_TEACHER || !$this->educater) {
                    return [];
                }
                return $this->educater->scopes;
            },
            'nation' => function() {
                if ($this->role_id == 0 || !$this->educater || !$this->educater->nation) {
                    return '';
                }
                return $this->educater->nation->name;
            },
            'grade' => function() {
                if ($this->role_id != Teacher::ROLE_ID_TEACHER || !$this->educater) {
                    return 0;
                }
                return $this->educater->grade_id;
            },
        ];
    }

}
